package com.example.my.shop.mybatis.controller;

import com.example.my.shop.mybatis.TbUser;
import com.example.my.shop.mybatis.service.Imp.TbUserServiceImpl;
import com.example.my.shop.mybatis.service.TbUserService;
import com.example.my.shop.mybatis.utils.CookieUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


@WebServlet(value = "/login")
public class LoginController extends HttpServlet {
    String cookieName = "UserInfo";
    String userSession = "userSession";

    /**
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         String cookieValue = CookieUtils.getCookieValue(req, cookieName);
         if (StringUtils.isNoneBlank(cookieValue)) {
            String[] arr = cookieValue.split(":");
            String email = arr[0];
            String password = arr[1];
            String rememberMe = "checked";

            req.setAttribute("email", email);
            req.setAttribute("password", password);
            req.setAttribute("rememberMe", rememberMe);
         }
         req.getRequestDispatcher("/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        String rememberMe = req.getParameter("rememberMe");

        TbUserService tbUserService = new TbUserServiceImpl();
        TbUser user = tbUserService.selectUserByEmail(email);

        if (user != null) {
            if(user.getPassword().equals(DigestUtils.md5Hex(password)) || password.equals(user.getPassword())){
                if ("on".equals(rememberMe)){
                    CookieUtils.setCookie(req, resp, cookieName, String.format("%s:%s", email,
                            DigestUtils.md5Hex(password)), 60*60*24*7);
                } else {
                    CookieUtils.deleteCookie(req, resp, cookieName);
                }

                req.getSession().setAttribute(userSession, user);

                resp.sendRedirect("main.jsp");
            } else {
                req.setAttribute("message", "wrong password");
                req.getRequestDispatcher("/login.jsp").forward(req, resp);
            }
        } else {
            req.setAttribute("message", "unable to log in");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
        }
    }
}
